#!/usr/bin/env node

const log=console.log,
      fileName=process.argv[3],
      opt=process.argv[2],
      fs=require('fs'),
      join=require('path').join;

function deleteDir(folder) {
  var files = fs.readdirSync(folder);

  for(var i=0; i<files.length; i++) {
    var file1 = join(folder, files[i]);

    if(fs.statSync(file1).isFile()) {
      fs.unlinkSync(file1);
      continue;
                            
    }

    if(fs.statSync(file1).isDirectory()) 
      deleteDir(file1);
                
  }

  fs.rmdirSync(folder);

} 

if(opt=='-list'){
  let file=fs.readdirSync(fileName);
  let arr=[];
  for(let i=0;i<file.length;i++){
    let f=file[i];
    let s=fs.statSync(fileName+'/'+file[i]).size;
    arr[i]={'fileName':`${f}`,'filesize':`${s}`};
  }
  arr.sort(function(a,b){
    return a.filesize-b.filesize;
  });
  log(JSON.stringify(arr,"",'\t'));
}
else if(opt=='-show'){
  let num=1;
  try{
    fs.readFileSync('sysFile/'+fileName).toString('utf8').split('\n').forEach((line)=>log(`${num++}\t${line}`));
  }catch(e){
    log('该文件不存在');
    process.exit();
  }
}
else if(opt=='-del'){
  let src=join('sysFile',fileName);
  if(typeof(src) === 'undefined') {
    console.error('请指定要删除的文件名或者目录名！');
    process.exit(1);
  }

  if(!fs.existsSync(src)) {
    console.error('%s not exist!', src);
    process.exit(2);
  }

  if(fs.statSync(src).isFile()){
    fs.unlinkSync(src);
    log('%s 删除成功',src);
    process.exit(3);
  }

  if(fs.statSync(src).isDirectory()){
    deleteDir(src);
    log('%s 删除成功',src);
    process.exit(4);
  }
}
